package com.example.broadcasttest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;
    private NetworkChangeReceiver networkChangeReceiver;


    //网络发生变化时，系统发出android.net.conn.CONNECTIVITY_CHANGE的一条广播
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intentFilter=new IntentFilter();
        //添加要监听的广播
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver=new NetworkChangeReceiver();
        registerReceiver(networkChangeReceiver,intentFilter);

        //发送标准广播
        Button button=findViewById(R.id.send_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent("com.example.broadcasttest.MY_BOADCAST");
                sendBroadcast(intent);
            }
        });
    }

    //动态注册的广播接收器一定都要注销
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(networkChangeReceiver);
    }

    //NetworkChangeReceiver继承自BroadcastReceiver，重写父类onReceive()，
    // 当收到监听的广播时，onReceive()就会执行
     class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
           // Toast.makeText(context,"网络改变",Toast.LENGTH_SHORT).show();
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            Network network = connectivityManager.getActiveNetwork();
            if(network == null){
                Toast.makeText(context,"网络无连接",Toast.LENGTH_SHORT).show();
            }
            else{
                NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
                assert networkCapabilities != null;
                if(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
                    Toast.makeText(context,"Cellular连接",Toast.LENGTH_SHORT).show();
                }
                if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
                    Toast.makeText(context,"WIFI连接",Toast.LENGTH_SHORT).show();
                }
            }

        }
    }
}
